package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.PeachBlossom;
import com.tanhua.dubbo.util.IdSequeue;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

/**
 * @author anshuai
 * @create 2021-03-01 11:23
 */
@Service
public class PeachBlossomApiImpl implements PeachBlossomApi {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdSequeue idSequeue;

    /**
     * 保存语音信息
     * @param peachBlossom 语音对象
     */
    @Override
    public void saveSound(PeachBlossom peachBlossom) {

        peachBlossom.setId(ObjectId.get());
        //因为mongodb单独保存key-value形式的数据,所以自增id字段只能以文档(集合)形式保存,所以随便给一个key做标识即可
        peachBlossom.setSid(idSequeue.getNextId("peachBlossom"));
        mongoTemplate.save(peachBlossom);
    }

    /**
     * 查询一条语音数据
     * @return
     */
    @Override
    public PeachBlossom findVoice(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("created")));
        if (query != null){
            return mongoTemplate.findOne(query,PeachBlossom.class);
        }

        return null;
    }
}
